<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="请输入关键字"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter="handleFilter"
      />
      <el-button class="filter-item" type="primary" @click="handleFilter">
        搜索
      </el-button>
      <el-upload
        class="filter-item"
        :action="null"
        :http-request="handleUpload"
        :show-file-list="false"
        :before-upload="beforeUpload"
      >
        <el-button type="primary">上传文件</el-button>
      </el-upload>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template #default="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="文件名称">
        <template #default="scope">
          {{ scope.row.fileName }}
        </template>
      </el-table-column>
      <el-table-column label="文件标识" width="290">
        <template #default="scope">
          {{ scope.row.fileKey }}
        </template>
      </el-table-column>
      <el-table-column label="文件大小" width="120" align="center">
        <template #default="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
            {{ scope.row.status === 'active' ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180" align="center">
        <template #default="scope">
          {{ formatDate(scope.row.createAt) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click="handleDownload(scope.row)"
          >
            下载
          </el-button>
          <el-button
            size="small"
            type="success"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="total > 0"
      :current-page="listQuery.current"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="listQuery.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑文件信息"
      v-model="dialogFormVisible"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left: 50px"
      >
        <el-form-item label="文件名称" prop="fileName">
          <el-input v-model="temp.fileName" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" style="width: 100%">
            <el-option label="正常" value="active" />
            <el-option label="禁用" value="inactive" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="temp.remark" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="updateData"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getFilePage,
  uploadFile,
  downloadFile,
  updateFile,
  deleteFile
} from '@/api/file';

// 数据列表
const list = ref([]);
const total = ref(0);
const listLoading = ref(true);
const dialogFormVisible = ref(false);
const dataForm = ref(null);

// 查询参数
const listQuery = reactive({
  current: 1,
  size: 10,
  keyword: ''
});

// 表单数据
const temp = reactive({
  id: undefined,
  fileName: '',
  fileKey: '',
  filePath: '',
  fileSize: 0,
  md5: '',
  status: 'active',
  remark: ''
});

// 表单验证规则
const rules = {
  fileName: [{ required: true, message: '请输入文件名称', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString();
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '0 B';
  
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 获取数据列表
const getList = () => {
  listLoading.value = true;
  getFilePage(listQuery)
    .then(response => {
      list.value = response.data.records;
      total.value = response.data.total;
      listLoading.value = false;
    })
    .catch(() => {
      listLoading.value = false;
    });
};

// 搜索
const handleFilter = () => {
  listQuery.current = 1;
  getList();
};

// 改变每页数量
const handleSizeChange = (val) => {
  listQuery.size = val;
  getList();
};

// 改变页码
const handleCurrentChange = (val) => {
  listQuery.current = val;
  getList();
};

// 上传前检查
const beforeUpload = (file) => {
  const isLt100M = file.size / 1024 / 1024 < 100;
  
  if (!isLt100M) {
    ElMessage.error('文件大小不能超过100MB!');
    return false;
  }
  
  return true;
};

// 上传文件
const handleUpload = (options) => {
  const { file } = options;
  
  // 创建表单数据
  const formData = new FormData();
  formData.append('file', file);
  
  // 弹出输入备注的对话框
  ElMessageBox.prompt('请输入文件备注', '上传文件', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPlaceholder: '请输入备注信息'
  }).then(({ value }) => {
    // 添加备注
    if (value) {
      formData.append('remark', value);
    }
    
    // 上传文件
    uploadFile(formData).then(response => {
      ElMessage({
        message: '上传成功',
        type: 'success'
      });
      getList();
    }).catch(error => {
      ElMessage.error('上传失败: ' + error.message);
    });
  }).catch(() => {
    // 取消上传
  });
};

// 下载文件
const handleDownload = (row) => {
  downloadFile(row.id).then(response => {
    // 创建Blob对象
    const blob = new Blob([response.data]);
    
    // 创建下载链接
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = row.fileName;
    link.click();
    
    // 释放URL对象
    URL.revokeObjectURL(link.href);
  }).catch(error => {
    ElMessage.error('下载失败: ' + error.message);
  });
};

// 编辑
const handleUpdate = (row) => {
  Object.assign(temp, row);
  dialogFormVisible.value = true;
};

// 更新数据
const updateData = () => {
  if (dataForm.value) {
    dataForm.value.validate((valid) => {
      if (valid) {
        updateFile(temp).then(() => {
          dialogFormVisible.value = false;
          ElMessage({
            message: '更新成功',
            type: 'success'
          });
          getList();
        });
      }
    });
  }
};

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该文件吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteFile(row.id).then(() => {
      ElMessage({
        message: '删除成功',
        type: 'success'
      });
      getList();
    });
  }).catch(() => {
    // 取消删除
  });
};

// 页面加载时获取数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.filter-container {
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}
.filter-item {
  margin-right: 10px;
}
</style> 